package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 静态资源工具
 */
public class StaticResourceUtil {

    // 获取静态资源文件路径
    public static String getAbsolutePath(String path){
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replace("\\\\", "/") + path;
    }

    // 读取静态文件，并通过输出流输出
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while (count == 0){
            count = inputStream.available();
        }
        int resourceSize = count;
        // 先输出 头部信息
        outputStream.write(HttpProtocolUtil.getHttpHead200(resourceSize).getBytes());

        // 已写入的 长度
        long written = 0;
        // 每次写入长度
        int byteSize = 1024;
        // 当前写入长度
        byte[] bytes = new byte[byteSize];

        while (written < resourceSize){
            if(written + byteSize > resourceSize){
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            // 读
            inputStream.read(bytes);
            // 些
            outputStream.write(bytes);
            // 刷新
            outputStream.flush();

            written += byteSize;
        }
    }
}
